﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
using HtmlAgilityPack;

namespace ZapHelper
{
    /// <summary>
    /// Basically, category scanner will link you to a products page 
    /// using the relevant category
    /// </summary>
    public abstract class CategoryParser
    {
        #region Properties
        
        #region Name

        public String Name { get; set; }

        #endregion

        #region Categories Url

        public Uri CategoriesUri { get; set; }
        
        #endregion

        #region Categories

        public IEnumerable<Category> Categories
        {
            get
            {
                return ParseCaterories();
            }
        } 
        #endregion

        #region Document

        private HtmlDocument m_document { get; set; }

        public HtmlDocument Document
        {
            get
            {
                if (m_document == null)
                {
                    // For thread safety
                    lock (this)
                    {
                        if (m_document == null)
                        {
                            // Create a new XmlDocument  
                            m_document = Utils.DownloadWebPage(CategoriesUri);
                        }
                    }
                }
                return m_document;
            }
        }

        #endregion

        #endregion

        #region Methods

        protected abstract IEnumerable<Category> ParseCaterories();
        
        public void ReloadFromCategoryParser(CategoryParser categoryParser)
        {
            if (categoryParser == null)
            {
                throw new ArgumentNullException("categoryParser");
            }

            this.Name = categoryParser.Name;
            this.m_document = categoryParser.Document;
            this.CategoriesUri = categoryParser.CategoriesUri;
        }

        #endregion
    }
}
